<template>
  <div class="withdrawal-management">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>提现管理</span>
        <div style="float: right;">
          <el-button 
            type="warning" 
            size="small" 
            icon="el-icon-setting"
            @click="handleAutoConfig"
            style="margin-right: 8px;">
            自动发货配置
          </el-button>
          <el-button 
            type="primary" 
            size="small" 
            icon="el-icon-plus"
            @click="handleAdd"
            style="margin-right: 8px;">
            新增提现渠道
          </el-button>
          <el-button 
            type="success" 
            size="small" 
            icon="el-icon-download"
            @click="exportData"
            :loading="exportLoading">
            导出CSV
          </el-button>
        </div>
      </div>

      <el-table
        :data="withdrawalChannels"
        border
        style="width: 100%"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
        v-loading="loading"
      >
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column prop="bank_name" label="银行名称" width="150"></el-table-column>
        <el-table-column prop="limit_low" label="最低提现" width="100"></el-table-column>
        <el-table-column prop="limit_high" label="最高提现" width="100"></el-table-column>
        <el-table-column prop="sort" label="排序" width="80"></el-table-column>
        <el-table-column prop="open" label="状态" width="180">
          <template slot-scope="scope">
            <el-switch
              :value="scope.row.open === 1"
              active-text="开启"
              inactive-text="关闭"
              @change="handleChangeStatus(scope.row, $event)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              @click="handleEdit(scope.row)">
              编辑
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新增/编辑弹窗 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="600px"
      @close="resetForm">
      <el-form
        :model="form"
        :rules="formRules"
        ref="form"
        label-width="100px">
        <el-form-item label="银行名称" prop="bank_name">
          <el-input v-model="form.bank_name" placeholder="请输入银行名称"></el-input>
        </el-form-item>
        <el-form-item label="最低提现" prop="limit_low">
          <el-input-number v-model="form.limit_low" :min="0" placeholder="最低提现金额"></el-input-number>
        </el-form-item>
        <el-form-item label="最高提现" prop="limit_high">
          <el-input-number v-model="form.limit_high" :min="0" placeholder="最高提现金额"></el-input-number>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="form.sort" :min="0" placeholder="排序值"></el-input-number>
        </el-form-item>
        <el-form-item label="状态" width="200" prop="open">
          <el-radio-group v-model="form.open">
            <el-radio :label="1">开启</el-radio>
            <el-radio :label="0">关闭</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="支付名称" prop="name" v-if="!isEdit">
          <el-input v-model="form.name" placeholder="请输入支付名称"></el-input>
        </el-form-item>
        <el-form-item label="支付标识" prop="tag" v-if="!isEdit">
          <el-input v-model="form.tag" placeholder="请输入支付标识"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          {{ isEdit ? '更新' : '新增' }}
        </el-button>
      </div>
    </el-dialog>

    <!-- 自动发货配置弹窗 -->
    <el-dialog
      title="自动发货配置"
      :visible.sync="autoConfigVisible"
      width="600px"
      @close="resetAutoForm">
      <el-form :model="autoForm" ref="autoForm" label-width="120px">
        <!-- 状态 -->
        <el-form-item label="状态">
          <el-radio-group v-model="autoForm.status">
            <el-radio :label="0">开启</el-radio>
            <el-radio :label="1">关闭</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 发货渠道 -->
        <el-form-item label="发货渠道">
          <el-select 
            v-model="autoForm.pay_channel" 
            placeholder="请选择发货渠道"
            clearable
            style="width: 100%;">
            <el-option
              v-for="channel in withdrawalChannelOptions"
              :key="channel.Id"
              :label="channel.bank_name"
              :value="channel.bank_name">
            </el-option>
          </el-select>
        </el-form-item>
        <el-divider></el-divider>
        <!-- 额度/次数/首充/倍率/卡号/IP/密码等 -->
        <el-form-item label="提现额度(IDR)">
          <el-input v-model="autoForm.cash_limit" type="number" placeholder="请输入提现额度"></el-input>
        </el-form-item>
        <el-form-item label="提现次数">
          <el-input v-model="autoForm.cash_count" type="number" placeholder="请输入提现次数"></el-input>
        </el-form-item>
        <el-form-item label="首充前金额">
          <el-input v-model="autoForm.first_pay_coin" type="number" placeholder="请输入首充前金额"></el-input>
        </el-form-item>
        <el-form-item label="时段发货倍率">
          <el-input v-model="autoForm.cash_ratio" type="number" placeholder="请输入时段发货倍率"></el-input>
        </el-form-item>
        <el-form-item label="总发货倍率">
          <el-input v-model="autoForm.cash_total_ratio" type="number" placeholder="请输入总发货倍率"></el-input>
        </el-form-item>
        <el-form-item label="关联卡号">
          <el-input v-model="autoForm.card_no" placeholder="请输入关联卡号"></el-input>
        </el-form-item>
        <el-form-item label="关联注册IP">
          <el-input v-model="autoForm.Ip" placeholder="请输入关联注册IP"></el-input>
        </el-form-item>
        <el-form-item label="关联密码">
          <el-input v-model="autoForm.password" type="password" placeholder="请输入关联密码"></el-input>
        </el-form-item>
        <el-divider></el-divider>

        <div style="text-align:right;margin-top:20px;">
          <el-button @click="autoConfigVisible = false">取消</el-button>
          <el-button type="primary" @click="handleAutoSubmit" :loading="autoSubmitLoading">保存</el-button>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { 
  cashoutChannel, 
  cashoutChannelOpen, 
  cashoutChannelAdd, 
  cashoutChannelEdit,
  cashoutAuto,
  cashoutAutoSave
} from '@/api/user'
import { exportDataToCsv } from '@/utils/export'
import channelMixin from '@/mixins/channelMixin'

export default {
  name: 'WithdrawalManagement',
  mixins: [channelMixin],
  data() {
    return {
      withdrawalChannels: [],
      loading: false,
      exportLoading: false,
      dialogVisible: false,
      dialogTitle: '',
      isEdit: false,
      form: {
        Id: '',
        bank_name: '',
        limit_low: 0,
        limit_high: 0,
        sort: 0,
        open: 1,
        name: '',
        tag: ''
      },
      submitLoading: false,
      autoConfigVisible: false,
      autoForm: {
        status: 0,
        pay_channel: '',
        cash_limit: 0,
        cash_count: 0,
        first_pay_coin: 0,
        cash_ratio: 0,
        cash_total_ratio: 0,
        card_no: '',
        Ip: '',
        password: ''
      },
      autoSubmitLoading: false,
      filterForm: {
        channel: null
      },
      withdrawalChannelOptions: []
    }
  },
  computed: {
    formRules() {
      const baseRules = {
        bank_name: [{ required: true, message: '请输入银行名称', trigger: 'blur' }],
        limit_low: [{ required: true, message: '请输入最低提现金额', trigger: 'blur' }],
        limit_high: [{ required: true, message: '请输入最高提现金额', trigger: 'blur' }]
      }
      
      // 只在新增时需要name和tag字段验证
      if (!this.isEdit) {
        baseRules.name = [{ required: true, message: '请输入支付名称', trigger: 'blur' }]
        baseRules.tag = [{ required: true, message: '请输入支付标识', trigger: 'blur' }]
      }
      
      return baseRules
    }
  },
  methods: {
    async handleChangeStatus(row, status) {
      this.loading = true
      try {
        const params = {
          id: row.Id,
          open: status ? 1 : 0
        }
        
        const response = await cashoutChannelOpen(params)
        
        if (response && response.code === 0) {
          row.open = status ? 1 : 0
          this.$message.success(`${row.bank_name} 状态已更新为 ${status ? '开启' : '关闭'}`)
        } else {
          this.$message.error(response.msg || response.message || '状态更新失败')
        }
      } catch (error) {
        console.error('更新提现渠道状态失败:', error)
        this.$message.error('状态更新失败')
      } finally {
        this.loading = false
      }
    },
    async fetchData() {
      this.loading = true
      try {
        const params = {
          channel: this.formatChannelParam(this.filterForm.channel)
        }
        const response = await cashoutChannel(params)
        
        if (response && response.code === 0) {
          // 处理可能的数据结构差异
          let channels = []
          if (response.data && response.data.Channels && Array.isArray(response.data.Channels)) {
            channels = response.data.Channels
          } else if (response.data && response.data.channels && Array.isArray(response.data.channels)) {
            channels = response.data.channels
          } else if (response.data && Array.isArray(response.data)) {
            channels = response.data
          } else if (response.data && typeof response.data === 'object') {
            for (let key in response.data) {
              if (Array.isArray(response.data[key])) {
                channels = response.data[key]
                break
              }
            }
          }
          
          this.withdrawalChannels = channels
          // 更新下拉选项数据
          this.withdrawalChannelOptions = channels
        } else {
          this.$message.error(response.msg || response.message || '获取数据失败')
        }
      } catch (error) {
        console.error('获取提现渠道数据失败:', error)
        this.$message.error('获取数据失败')
      } finally {
        this.loading = false
      }
    },
    handleAdd() {
      this.isEdit = false
      this.dialogTitle = '新增提现渠道'
      this.form = {
        bank_name: '',
        limit_low: 0,
        limit_high: 0,
        sort: 0,
        open: 1,
        name: '',
        tag: ''
      }
      this.dialogVisible = true
      // 清除表单验证
      this.$nextTick(() => {
        if (this.$refs.form) {
          this.$refs.form.clearValidate()
        }
      })
    },
    handleEdit(row) {
      this.isEdit = true
      this.dialogTitle = '编辑提现渠道'
      this.form = { 
        Id: row.Id,
        bank_name: row.bank_name,
        limit_low: row.limit_low,
        limit_high: row.limit_high,
        sort: row.sort,
        open: row.open,
        name: '', // 编辑时清空，因为修改接口不需要
        tag: ''   // 编辑时清空，因为修改接口不需要
      }
      this.dialogVisible = true
      // 清除表单验证
      this.$nextTick(() => {
        if (this.$refs.form) {
          this.$refs.form.clearValidate()
        }
      })
    },
    resetForm() {
      if (this.$refs.form) {
        this.$refs.form.resetFields()
      }
    },
    async handleSubmit() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          this.submitLoading = true
          try {
            let params
            let response
            
            if (this.isEdit) {
              // 修改接口参数 - 必须包含id，不包含name和tag
              params = {
                id: this.form.Id,
                bank_name: this.form.bank_name,
                limit_low: parseInt(this.form.limit_low) || 0,
                limit_high: parseInt(this.form.limit_high) || 0,
                sort: parseInt(this.form.sort) || 0,
                open: this.form.open ? 1 : 0
              }
              response = await cashoutChannelEdit(params)
            } else {
              // 新增接口参数 - 不包含ID，但包含name和tag
              params = {
                bank_name: this.form.bank_name,
                limit_low: parseInt(this.form.limit_low) || 0,
                limit_high: parseInt(this.form.limit_high) || 0,
                sort: parseInt(this.form.sort) || 0,
                open: this.form.open ? 1 : 0,
                name: this.form.name,
                tag: this.form.tag
              }
              response = await cashoutChannelAdd(params)
            }

            console.log('提交参数:', params)
            console.log('接口响应:', response)

            if (response && response.code === 0) {
              this.$message.success(`${this.isEdit ? '更新' : '新增'}成功！`)
              this.dialogVisible = false
              this.fetchData()
            } else {
              this.$message.error(response.msg || response.message || `${this.isEdit ? '更新' : '新增'}失败`)
            }
          } catch (error) {
            console.error(`${this.isEdit ? '更新' : '新增'}失败:`, error)
            this.$message.error(`${this.isEdit ? '更新' : '新增'}失败`)
          } finally {
            this.submitLoading = false
          }
        }
      })
    },
    async handleAutoConfig() {
      this.autoConfigVisible = true
      
      // 确保提现渠道数据已加载
      if (this.withdrawalChannelOptions.length === 0) {
        await this.fetchData()
      }
      
      try {
        const response = await cashoutAuto()
        if (response && response.code === 0) {
          // 根据接口文档，直接使用返回的数据
          this.autoForm = { ...response.data }
          console.log('获取自动发货配置成功:', this.autoForm)
        } else {
          // 如果没有数据，使用默认值
          this.resetAutoForm()
          console.log('获取自动发货配置失败，使用默认值')
        }
      } catch (error) {
        console.error('获取自动配置失败:', error)
        // 出错时使用默认值
        this.resetAutoForm()
      }
    },
    resetAutoForm() {
      this.autoForm = {
        status: 0,
        pay_channel: '',
        cash_limit: 0,
        cash_count: 0,
        first_pay_coin: 0,
        cash_ratio: 0,
        cash_total_ratio: 0,
        card_no: '',
        Ip: '',
        password: ''
      }
    },
    async handleAutoSubmit() {
      this.autoSubmitLoading = true
      try {
        // 根据接口文档构建参数
        const params = {
          status: this.autoForm.status,
          pay_channel: this.autoForm.pay_channel,
          cash_limit: parseInt(this.autoForm.cash_limit) || 0,
          cash_count: parseInt(this.autoForm.cash_count) || 0,
          first_pay_coin: parseInt(this.autoForm.first_pay_coin) || 0,
          cash_ratio: parseFloat(this.autoForm.cash_ratio) || 0,
          cash_total_ratio: parseFloat(this.autoForm.cash_total_ratio) || 0,
          card_no: this.autoForm.card_no || '',
          Ip: this.autoForm.Ip || '',
          password: this.autoForm.password || ''
        }
        
        console.log('提交自动发货配置参数:', params)
        const response = await cashoutAutoSave(params)
        
        if (response && response.code === 0) {
          this.$message.success('自动发货配置保存成功！')
          this.autoConfigVisible = false
        } else {
          this.$message.error(response.msg || response.message || '保存失败')
        }
      } catch (error) {
        console.error('保存自动配置失败:', error)
        this.$message.error('保存失败')
      } finally {
        this.autoSubmitLoading = false
      }
    },
    async exportData() {
      this.exportLoading = true
      try {
        const response = await cashoutChannel()
        let allData = []
        
        if (response.data && response.data.Channels && Array.isArray(response.data.Channels)) {
          allData = response.data.Channels
        } else if (response.data && response.data.channels && Array.isArray(response.data.channels)) {
          allData = response.data.channels
        } else if (response.data && Array.isArray(response.data)) {
          allData = response.data
        }
        
        const columns = [
          { prop: 'Id', label: 'ID' },
          { prop: 'bank_name', label: '银行名称' },
          { prop: 'limit_low', label: '最低提现' },
          { prop: 'limit_high', label: '最高提现' },
          { prop: 'sort', label: '排序' },
          { prop: 'open', label: '状态', formatter: (row) => row.open === 1 ? '开启' : '关闭' }
        ]
        
        const now = new Date()
        const dateStr = now.getFullYear() + 
          String(now.getMonth() + 1).padStart(2, '0') + 
          String(now.getDate()).padStart(2, '0') + '_' +
          String(now.getHours()).padStart(2, '0') + 
          String(now.getMinutes()).padStart(2, '0')
        
        const fileName = `提现管理_${dateStr}.csv`
        exportDataToCsv(allData, columns, fileName)
        this.$message.success('导出成功！')
      } catch (error) {
        this.$message.error('导出失败')
        console.error(error)
      } finally {
        this.exportLoading = false
      }
    },
    resetFilter() {
      this.filterForm.channel = null
      this.fetchData()
    }
  },
  mounted() {
    this.fetchData()
  }
}
</script>

<style scoped>
.withdrawal-management {
  padding: 20px;
}
</style> 